import Taro, { getCurrentInstance } from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { View, Text, Button } from '@tarojs/components';
import { AtDivider, AtToast, AtCheckbox, AtMessage } from 'taro-ui';
import { getSurveyDetail, submitVote } from '@/api/application/pollsandSurvey/index';
import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "taro-ui/dist/style/components/divider.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/fab.scss";
import "taro-ui/dist/style/components/radio.scss";
import "taro-ui/dist/style/components/checkbox.scss";
import Header from '@/components/header';
import Return from '@/components/Return';
import css from './index.module.less';
import "./index.less";

export default function SurveyDetail() {
  //投票详情
  const [voteDetail, setVoteDetail] = useState({});
  //多选选项数据
  const [selectsData, setSelectsData] = useState([]);
  //用户选择的选项
  const [selectedList, setSelectedList] = useState([]);
  //加载中
  const [isOpened, setIsOpened] = useState(false);

  const router = getCurrentInstance().router.params;
  const { voteId, partyId } = JSON.parse(decodeURIComponent(router.data));

  useEffect(() => {
    getSurveyDetail(voteId, partyId).then((res) => {
      if (res.code === 200) {
        setVoteDetail(res.data);
        const { optionRecord, voteOptionList } = res.data;
        //填装选项数据
        const disabled = res.data.optionRecord.length ? true : false;
        res.data.voteOptionList.forEach(item => {
          selectsData.push({ value: item.id, label: `${item.option}. ${item.optionContent}`, disabled });
        });
        setSelectsData([...selectsData]);
        if (disabled) {
          const temp = [];
          optionRecord.forEach(option => {
            voteOptionList.forEach(vote => {
              if (vote.option == option) temp.push(vote.id);
            });
          });
          setSelectedList(temp);
        }
        else {
          //默认选中第一个选项
          setSelectedList([voteOptionList[0].id]);
        }
      }
      else console.log(res);
    }).catch(err => { console.log(err); });
  }, []);

  const selectChange = (values) => {
    if (values.length !== 0) {
      const value = values[values.length - 1];
      setSelectedList([value]);
    }
  };

  const selectsChange = (values) => {
    setSelectedList(values);
  };

  const submitSelect = () => {
    if (selectedList.length === 0) {
      Taro.atMessage({ 'message': '请至少选择一个选项', 'type': 'warning', 'duration': 2000 });
    }
    else {
      setIsOpened(true);
      const data = {
        voteId, partyId,
        optionIdList: selectedList
      };
      submitVote(data).then(res => {
        if (res.code === 200) {
          Taro.navigateBack();
        }
      }).finally(() => { setIsOpened(true); });
    }
  };

  return (
    <View className={css.home}>
      <Header message='投票调查' left='140px' />
      <Return />
      <View className={css.content}>
        <AtMessage />
        <View className={css.topCon}>
          <View className={css.sponsorName}>发起人：{voteDetail.sponsorName}</View>
          <View className={css.organizationName}>({voteDetail.organizationName})</View>
          <View className={css.endTime}>{voteDetail.voteEndTime}截止</View>
        </View>

        <AtDivider lineColor='#999999' className={css.divider} />

        <View className={css.middleCon}>
          <Text>{voteDetail.voteTitle}</Text>
          <View className={css.voteCon}>{voteDetail.voteContent}</View>
        </View>

        <View className={css.selectCon}>
          <View className={css.voteType}>选项:{voteDetail.voteType === 1 ? ' 单选' : ' 多选'}</View>
          <View className={css.selectList}>
            {
              voteDetail.voteType === 1 ?
                <View>
                  <AtCheckbox selectedList={selectedList} options={selectsData} onChange={selectChange} />
                </View> :
                <View>
                  <AtCheckbox selectedList={selectedList} options={selectsData} onChange={selectsChange} />
                </View>
            }
          </View>
        </View>

        {
          voteDetail.optionRecord === undefined || voteDetail.optionRecord.length === 0 ?
            <View>
              <Button className={css.unsubmit} onClick={submitSelect}>提交</Button>
            </View> :
            <View>
              <Button className={css.submited}>已提交</Button>
            </View>
        }

      </View>

      <AtToast isOpened={isOpened} text='上传数据中...' status='loading' duration={0} hasMask />
    </View>
  );
}